<?php

namespace app\http\middleware;

use leruge\auth\AuthFacade;
use think\facade\View;

class AdminLoginCheck
{
    public function handle($request, \Closure $next)
    {
        if (session('?adminId')) {
            $adminInfo = model('Admin')::get(session('adminId'));
            if ($adminInfo) {
                if ($adminInfo['status'] == 1) {
                    return $this->online($request, $next);
                } else {
                    return $this->offline();
                }
            } else {
                return $this->offline();
            }
        } else {
            return $this->offline();
        }
    }

    // 正常处理
    private function online($request, $next)
    {
        $isAccess = false;
        $dispatch = request()->module() . '/' . request()->controller() . '/' . request()->action();
        if (AuthFacade::check($dispatch, session('adminId'))) {
            $isAccess = true;
        }

        // wdl开头的方法不需要权限
        if (substr(request()->action(), 0, 3) == 'wdl') {
            $isAccess = true;
        }

        if ($isAccess) {
            // 共享视图
            $viewData = [];
            View::share($viewData);
            return $next($request);
        } else {
            return $this->noAuth();
        }
    }

    // 掉线处理
    private function offline()
    {
        session(null);
        return redirect('admin/login/login', '', 302);
    }

    // 无权限
    private function noAuth()
    {
        return redirect('admin/home/wdlNoAuth', '', 403);
    }
}
